<script setup lang="ts">
import { ref, onMounted, watch, nextTick, onUnmounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { showToast } from 'vant'
import { useI18n } from '@/utils/i18n'; // 导入国际化工具

// 国际化功能
const { t } = useI18n();

// 防抖函数
const debounce = (fn: Function, delay: number) => {
  let timeoutId: NodeJS.Timeout
  return (...args: any[]) => {
    clearTimeout(timeoutId)
    timeoutId = setTimeout(() => fn.apply(null, args), delay)
  }
}

// 获取路由器实例
const router = useRouter()

// 返回上一页方法
const goBack = () => {
  router.back()
}

// 定义消息类型
interface Message {
  id: number
  content: string
  type: 'user' | 'ai'
  timestamp: Date
  thinking?: string[] // 添加思考过程属性
  image?: string // 添加图片属性
  video?: string // 添加视频属性
  status?: 'sending' | 'sent' | 'failed' | 'retry' // 新增状态
  retryCount?: number // 重试次数
}

// 定义常用问题类型
interface QuickQuestion {
  id: number
  text: string
}

// 用户偏好和上下文记忆
interface UserProfile {
  fitnessLevel: 'beginner' | 'intermediate' | 'advanced'
  goals: string[]
  preferences: string[]
  restrictions: string[]
}

// 定义聊天消息内容类型
interface TextContent {
  type: 'text'
  text: string
}

interface ImageContent {
  type: 'image_url'
  image_url: {
    url: string
  }
}

interface ChatMessage {
  role: 'system' | 'user' | 'assistant'
  content: string | (TextContent | ImageContent)[]
}

// 聊天历史
const chatHistory = ref<Message[]>([])
// 用户输入
const userInput = ref('')
// 是否正在加载回复
const isLoading = ref(false)
// 会话ID
const sessionId = ref('')
// 用户ID
const userId = 'user_' + Date.now()
// 是否显示思考过程
const showThinking = ref(true)
// 当前思考步骤
const currentThinkingStep = ref('')
// 思考步骤列表
const thinkingSteps = ref<string[]>([])
// 常用问题列表
const quickQuestions = ref<QuickQuestion[]>([
  { id: 1, text: t('quickQuestion1') },
  { id: 2, text: t('quickQuestion2') },
  { id: 3, text: t('quickQuestion3') },
  { id: 4, text: t('quickQuestion4') }
])

const userProfile = ref<UserProfile>({
  fitnessLevel: 'beginner',
  goals: [],
  preferences: [],
  restrictions: []
})
// 当前流式回复
const currentStreamingReply = ref('')
// 是否使用流式输出
const useStreaming = ref(true)
// 添加图片相关的响应式变量
const selectedImage = ref<File | null>(null)
const imagePreview = ref<string>('')
const isUploading = ref(false)
// 视频上传和分析
const selectedVideo = ref<File | null>(null)
const videoPreview = ref('')
// 添加请求取消控制
const abortController = ref<AbortController | null>(null)
// 添加回退功能的状态管理
const canUndo = ref(false)
const currentRequestController = ref<AbortController | null>(null)

// 合并重复的计算属性
const buttonState = computed(() => ({
  text: isUploading.value ? '处理中...' : '发送',
  icon: '📤',
  disabled: isUploading.value || (!userInput.value.trim() && !selectedImage.value && !selectedVideo.value)
}))
// 添加常见问题显示状态
const showQuickQuestions = ref(false)

// 切换常见问题显示状态
const toggleQuickQuestions = () => {
  showQuickQuestions.value = !showQuickQuestions.value
}

// 计算属性：是否显示常见问题
const shouldShowQuickQuestions = computed(() => {
  // 只有用户消息少于3条时才显示（排除AI回复）
  const userMessages = chatHistory.value.filter(msg => msg.type === 'user')
  return userMessages.length < 3
})

// 添加聊天状态枚举
enum ChatState {
  IDLE = 'idle',
  THINKING = 'thinking',
  STREAMING = 'streaming'
}

const chatState = ref<ChatState>(ChatState.IDLE)

// 回退到上一步
const undoLastMessage = () => {
  if (canUndo.value) {
    // 删除最后两条消息（用户消息和AI回复）
    if (chatHistory.value.length > 2) {
      chatHistory.value.splice(-2, 2)
    } else if (chatHistory.value.length > 1) {
      chatHistory.value.pop()
    }
    canUndo.value = false
    chatState.value = ChatState.IDLE
    
    showToast(t('undoSuccess'))
  }
}

// 撤销最后一条消息
const deleteLastMessage = () => {
  if (chatHistory.value.length > 1) { // 保留欢迎消息
    // 如果最后一条是AI消息，删除对应的用户消息
    const lastMessage = chatHistory.value[chatHistory.value.length - 1]
    if (lastMessage.type === 'ai' && chatHistory.value.length > 1) {
      chatHistory.value.pop() // 删除AI消息
      if (chatHistory.value[chatHistory.value.length - 1].type === 'user') {
        chatHistory.value.pop() // 删除对应的用户消息
      }
    } else {
      chatHistory.value.pop() // 只删除最后一条消息
    }
    
    showToast(t('deleteSuccess'))
  }
}

// 硅基流动API配置
const SILICONFLOW_API_KEY = 'sk-dcjkzeqakvgowmyxxmuozahyaxdzbxziopgndjrlblqrwote' // 请替换为你的API密钥
const SILICONFLOW_API_URL = 'https://api.siliconflow.cn/v1/chat/completions'
// 简化文件上传验证
const validateFile = (file: File, type: 'image' | 'video') => {
  const configs = {
    image: { types: ['image/jpeg', 'image/png', 'image/gif', 'image/webp'], maxSize: 5 * 1024 * 1024 },
    video: { types: ['video/mp4', 'video/webm', 'video/ogg'], maxSize: 50 * 1024 * 1024 }
  }
  const config = configs[type]
  
  if (!config.types.includes(file.type)) {
    showToast(`仅支持 ${config.types.join('、')} 格式`)
    return false
  }
  if (file.size > config.maxSize) {
    showToast(`文件大小不能超过${config.maxSize / 1024 / 1024}MB`)
    return false
  }
  return true
}

// 合并图片和视频上传处理
const handleFileUpload = (event: Event, type: 'image' | 'video') => {
  const file = (event.target as HTMLInputElement).files?.[0]
  if (!file || !validateFile(file, type)) return
  
  if (type === 'image') {
    // 添加图片尺寸检查
    const img = new Image()
    img.onload = () => {
      if (img.width > 4096 || img.height > 4096) {
        showToast('图片尺寸过大，请选择较小的图片')
        return
      }
      selectedImage.value = file
      imagePreview.value = URL.createObjectURL(file)
      showToast('图片上传成功')
    }
    img.onerror = () => {
      showToast('图片格式不正确或已损坏')
    }
    img.src = URL.createObjectURL(file)
  } else {
    selectedVideo.value = file
    videoPreview.value = URL.createObjectURL(file)
    showToast('视频上传成功，可以请AI分析您的运动姿势')
  }
}

// 图片上传处理函数
const handleImageUpload = (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  
  if (!file) return
  
  // 添加更严格的文件验证
  const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']
  if (!allowedTypes.includes(file.type)) {
    showToast(t('imageTypeError'))
    return
  }
  
  // 添加文件大小检查
  const maxSize = 5 * 1024 * 1024 // 5MB
  if (file.size > maxSize) {
    showToast(t('imageSizeError'))
    return
  }
  
  // 添加图片尺寸检查
  const img = new Image()
  img.onload = () => {
    if (img.width > 4096 || img.height > 4096) {
      showToast(t('imageDimensionError'))
      return
    }
    
    // 生成预览
    selectedImage.value = file
    imagePreview.value = URL.createObjectURL(file)
  }
  img.onerror = () => {
    showToast(t('imageFormatError'))
  }
  img.src = URL.createObjectURL(file)
  handleFileUpload(event, 'image')
}

// 处理视频上传
const handleVideoUpload = (event: Event) => {
  handleFileUpload(event, 'video')
}

// 合并移除文件函数
const removeFile = (type: 'image' | 'video') => {
  if (type === 'image') {
    selectedImage.value = null
    imagePreview.value = ''
  } else {
    selectedVideo.value = null
    videoPreview.value = ''
  }
  const input = document.getElementById(`${type}Input`) as HTMLInputElement
  if (input) input.value = ''
}

// 移除选中的图片
const removeImage = () => {
  selectedImage.value = null
  if (imagePreview.value) {
    URL.revokeObjectURL(imagePreview.value)
    imagePreview.value = ''
  }
  // 清空文件输入框
  const fileInput = document.getElementById('imageInput') as HTMLInputElement
  if (fileInput) {
    fileInput.value = ''
  }
  removeFile('image')
}

// 移除选中的视频
const removeVideo = () => {
  removeFile('video')
}

// 动作识别分析
const analyzeWorkoutForm = async (videoFile: File) => {
  // 集成姿态识别API或本地模型
  // 分析运动姿势的正确性
  return {
    accuracy: 85,
    suggestions: ['保持背部挺直', '动作幅度可以更大'],
    riskAreas: ['膝盖角度需要注意']
  }
}

// 将图片转换为base64
const imageToBase64 = (file: File): Promise<string> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = () => {
      const base64 = reader.result as string
      // 移除data:image/...;base64,前缀
      const base64Data = base64.split(',')[1]
      resolve(base64Data)
    }
    reader.onerror = reject
    reader.readAsDataURL(file)
  })
}

// 添加重试逻辑
const retryRequest = async (fn: () => Promise<any>, maxRetries = 3): Promise<any> => {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await fn()
    } catch (error) {
      if (i === maxRetries - 1) throw error
      
      // 指数退避
      await new Promise(resolve => setTimeout(resolve, Math.pow(2, i) * 1000))
    }
  }
  throw new Error(t('maxRetriesReached'))
}

// 调用硅基流动AI模型
const callSiliconFlowAI = async (
  message: string, 
  imageBase64?: string, 
  signal?: AbortSignal
): Promise<string> => {
  try {
    const messages: ChatMessage[] = [
      {
        role: 'system',
        content: t('systemPrompt')
      }
    ]
    
    if (imageBase64) {
      messages.push({
        role: 'user',
        content: [
          {
            type: 'text',
            text: message
          },
          {
            type: 'image_url',
            image_url: {
              url: `data:image/jpeg;base64,${imageBase64}`
            }
          }
        ]
      })
    } else {
      messages.push({
        role: 'user',
        content: message
      })
    }
    
    const response = await axios.post(SILICONFLOW_API_URL, {
      model: 'Qwen/Qwen2-VL-72B-Instruct', // 使用支持视觉的模型
      messages: messages,
      temperature: 0.7,
      max_tokens: 1000,
      stream: false
    }, {
      headers: {
        'Authorization': `Bearer ${SILICONFLOW_API_KEY}`,
        'Content-Type': 'application/json'
      },
      signal // 添加取消信号
    })

    return response.data.choices[0].message.content
  } catch (error) {
    console.error('硅基流动API调用失败:', error)
    throw error
  }
}

// 流式调用硅基流动AI模型
const callSiliconFlowAIStream = async (
  message: string,
  onToken: (token: string) => void,
  onThinking: (step: string) => void,
  imageBase64?: string,
  signal?: AbortSignal
): Promise<void> => {
  try {
    const messages: ChatMessage[] = [
      {
        role: 'system',
        content: t('systemPrompt')
      }
    ]
    
    if (imageBase64) {
      // 硅基流动API的多模态消息格式
      messages.push({
        role: 'user',
        content: [
          {
            type: 'text',
            text: message
          },
          {
            type: 'image_url',
            image_url: {
              url: `data:image/jpeg;base64,${imageBase64}`
            }
          }
        ]
      })
    } else {
      messages.push({
        role: 'user',
        content: message
      })
    }
    
    const response = await fetch(SILICONFLOW_API_URL, {
      method: 'POST',
      signal: signal,
      headers: {
        'Authorization': `Bearer ${SILICONFLOW_API_KEY}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        model: 'Qwen/Qwen2-VL-72B-Instruct', // 使用支持视觉的模型
        messages: messages,
        temperature: 0.7,
        max_tokens: 1000,
        stream: true
      })
    })

    if (!response.ok) {
      throw new Error(`${t('apiError')}: ${response.status}`)
    }

    const reader = response.body?.getReader()
    const decoder = new TextDecoder()

    if (!reader) {
      throw new Error(t('streamError'))
    }

    // 多语言思考步骤
    const thinkingSteps = imageBase64 
      ? [
          t('thinkingAnalyzeImage'),
          t('thinkingIdentifyContent'),
          t('thinkingProvideAdvice')
        ]
      : [
          t('thinkingAnalyzeQuestion'),
          t('thinkingRetrieveKnowledge'),
          t('thinkingOrganizeAnswer')
        ]

    // 显示思考过程
    for (let i = 0; i < thinkingSteps.length; i++) {
      onThinking(thinkingSteps[i])
      await new Promise(resolve => setTimeout(resolve, 800))
    }

    while (true) {
      const { done, value } = await reader.read()
      if (done) break

      const chunk = decoder.decode(value)
      const lines = chunk.split('\n')

      for (const line of lines) {
        if (line.startsWith('data: ')) {
          const data = line.slice(6)
          if (data === '[DONE]') {
            return
          }

          try {
            const parsed = JSON.parse(data)
            const content = parsed.choices?.[0]?.delta?.content
            if (content) {
              onToken(content)
            }
          } catch (e) {
            // 忽略解析错误
          }
        }
      }
    }
  } catch (error) {
    console.error('硅基流动流式API调用失败:', error)
    throw error
  }
}

// 模拟AI思考过程（多语言支持）
const simulateThinking = (question: string): string[] => {
  const thoughts = [
    t('thinkingStep1'),
    t('thinkingStep2'),
    t('thinkingStep3'),
    t('thinkingStep4')
  ]
  
  // 根据问题类型添加特定的思考过程
  if (question.includes(t('quickQuestion1').toLowerCase()) || question.includes(t('workoutPlanKeyword'))) {
    thoughts.push(t('thinkingPlan1'))
    thoughts.push(t('thinkingPlan2'))
  } else if (question.includes(t('quickQuestion2').toLowerCase()) || question.includes(t('muscleSorenessKeyword'))) {
    thoughts.push(t('thinkingSoreness1'))
    thoughts.push(t('thinkingSoreness2'))
  } else if (question.includes(t('quickQuestion3').toLowerCase()) || question.includes(t('beginnerKeyword')) || question.includes(t('exerciseKeyword'))) {
    thoughts.push(t('thinkingExercise1'))
    thoughts.push(t('thinkingExercise2'))
  } else if (question.includes(t('quickQuestion4').toLowerCase()) || question.includes(t('durationKeyword'))) {
    thoughts.push(t('thinkingDuration1'))
    thoughts.push(t('thinkingDuration2'))
  }
  
  return thoughts
}

// 发送消息方法
const sendMessage = async () => {
  if (!userInput.value.trim() && !selectedImage.value) return
  
  let imageBase64: string | undefined
  
  // 创建新的AbortController
  currentRequestController.value = new AbortController()
  
  // 如果有选中的图片，转换为base64
  if (selectedImage.value) {
    try {
      isUploading.value = true
      imageBase64 = await imageToBase64(selectedImage.value)
    } catch (error) {
      console.error('图片处理失败:', error)
      showToast(t('imageProcessError'))
      isUploading.value = false
      return
    } finally {
      isUploading.value = false
    }
  }
  
  // 如果有选中的视频，进行分析
  if (selectedVideo.value) {
    try {
      isUploading.value = true
      const analysis = await analyzeWorkoutForm(selectedVideo.value)
      // 将分析结果添加到用户消息中
      userInput.value = userInput.value || '请分析我的运动视频'
    } catch (error) {
      console.error('视频分析失败:', error)
      showToast('视频分析失败，请重试')
      isUploading.value = false
      return
    } finally {
      isUploading.value = false
    }
  }
  
  // 添加用户消息到历史记录
  const userMessage: Message = {
    id: Date.now(),
    content: userInput.value || (selectedImage.value ? '请分析这张图片' : '请分析这个视频'),
    type: 'user',
    timestamp: new Date(),
    image: imagePreview.value || undefined,
    video: videoPreview.value || undefined,
    status: 'sent'
  }
  chatHistory.value.push(userMessage)
  
  // 清空输入框并显示加载状态
  const question = userInput.value || (selectedImage.value ? '请分析这张图片' : '请分析这个视频')
  userInput.value = ''
  // 清空图片和视频选择
  removeImage()
  removeVideo()
  isLoading.value = true
  chatState.value = ChatState.THINKING
  
  // 重置思考步骤
  thinkingSteps.value = []
  currentThinkingStep.value = ''
  
  try {
    if (useStreaming.value) {
      chatState.value = ChatState.STREAMING
      currentStreamingReply.value = ''
      // 添加一个空的AI回复消息，用于流式更新
      const aiResponseId = Date.now() + 1
      const aiMessage: Message = {
        id: aiResponseId,
        content: '',
        type: 'ai',
        timestamp: new Date(),
        status: 'sending'
      }
      chatHistory.value.push(aiMessage)
      
      // 使用硅基流动流式API
      await callSiliconFlowAIStream(
        question,
        // 文本token回调
        (token) => {
          const lastMessage = chatHistory.value[chatHistory.value.length - 1]
          if (lastMessage && lastMessage.type === 'ai') {
            lastMessage.content += token
          }
        },
        // 思考步骤回调
        (step) => {
          currentThinkingStep.value = step
          thinkingSteps.value.push(step)
        },
        imageBase64,
        currentRequestController.value.signal // 添加取消信号
      )
      
      // 更新最后一条消息的思考过程
      const lastMessage = chatHistory.value[chatHistory.value.length - 1]
      if (lastMessage && lastMessage.type === 'ai') {
        lastMessage.thinking = [...thinkingSteps.value]
        lastMessage.status = 'sent'
      }
      
      // 设置可以回退
      canUndo.value = true
      
    } else {
      // 非流式实现
      // 模拟思考过程的显示
      thinkingSteps.value = imageBase64 
        ? [
            t('thinkingAnalyzeImage'),
            t('thinkingIdentifyContent'),
            t('thinkingProvideAdvice')
          ]
        : simulateThinking(question)
      
      let currentStep = 0
      const thinkInterval = setInterval(() => {
        if (currentStep < thinkingSteps.value.length) {
          currentThinkingStep.value = thinkingSteps.value[currentStep]
          currentStep++
        } else {
          clearInterval(thinkInterval)
          currentThinkingStep.value = ''
        }
      }, 800)
      
      // 调用硅基流动AI
      const aiResponse = await retryRequest(() => callSiliconFlowAI(question, imageBase64, currentRequestController.value?.signal))
      
      // 清除思考过程显示
      clearInterval(thinkInterval)
      currentThinkingStep.value = ''
      
      // 添加AI回复到聊天历史
      const aiMessage: Message = {
        id: Date.now() + 1,
        content: aiResponse,
        type: 'ai',
        timestamp: new Date(),
        thinking: [...thinkingSteps.value],
        status: 'sent'
      }
      chatHistory.value.push(aiMessage)
      
      // 设置可以回退
      canUndo.value = true
    }
    
    chatState.value = ChatState.IDLE
    isLoading.value = false
    currentThinkingStep.value = ''
    
  } catch (error:any) {
    if (error.name === 'AbortError') {
      console.log(t('requestCancelled'))
      return
    }
    
    console.error('AI响应失败:', error)
    
    // 移除空的AI消息（如果是流式模式）
    if (useStreaming.value && chatHistory.value.length > 0) {
      const lastMessage = chatHistory.value[chatHistory.value.length - 1]
      if (lastMessage && lastMessage.type === 'ai' && !lastMessage.content) {
        chatHistory.value.pop()
      }
    }
    
    // 添加错误提示
    const errorMessage: Message = {
      id: Date.now() + 1,
      content: t('aiResponseError'),
      type: 'ai',
      timestamp: new Date(),
      status: 'failed',
      retryCount: 0
    }
    chatHistory.value.push(errorMessage)
    
    chatState.value = ChatState.IDLE
    isLoading.value = false
    currentThinkingStep.value = ''
  }
}

// 切换流式输出模式
const toggleStreamingMode = () => {
  useStreaming.value = !useStreaming.value
}

// 选择快速问题
const selectQuickQuestion = (question: QuickQuestion) => {
  userInput.value = question.text
  sendMessage()
}

// 切换显示思考过程
const toggleThinking = () => {
  showThinking.value = !showThinking.value
}

// 滚动到最新消息
const scrollToBottom = () => {
  const chatContainer = document.querySelector('.chat-messages')
  if (chatContainer) {
    chatContainer.scrollTop = chatContainer.scrollHeight
  }
}

// 监听消息变化，自动滚动
watch(chatHistory, () => {
  nextTick(() => {
    scrollToBottom()
  })
}, { deep: true })

// 监听思考步骤变化，自动滚动
watch(currentThinkingStep, () => {
  nextTick(() => {
    scrollToBottom()
  })
})

// 监听流式回复变化，自动滚动
watch(() => {
  // 找到最后一条AI消息
  const lastMessage = chatHistory.value[chatHistory.value.length - 1]
  return lastMessage?.content
}, () => {
  nextTick(() => {
    scrollToBottom()
  })
})

// 添加重试功能
const retryMessage = async (messageId: number) => {
  const message = chatHistory.value.find(m => m.id === messageId)
  if (message && (message.retryCount || 0) < 3) {
    message.status = 'sending'
    message.retryCount = (message.retryCount || 0) + 1
    
    // 重新发送逻辑
    const question = message.content
    let imageBase64: string | undefined
    
    // 如果消息包含图片，需要重新处理（这里简化处理）
    if (message.image) {
      console.log(t('retryImageMessage'))
    }
    
    isLoading.value = true
    thinkingSteps.value = []
    currentThinkingStep.value = ''
    
    try {
      if (useStreaming.value) {
        // 流式重试
        await callSiliconFlowAIStream(
          question,
          (token) => {
            message.content += token
          },
          (step) => {
            currentThinkingStep.value = step
            thinkingSteps.value.push(step)
          },
          imageBase64,
          currentRequestController.value.signal
        )
        message.thinking = [...thinkingSteps.value]
        message.status = 'sent'
      } else {
        // 非流式重试
        const aiResponse = await retryRequest(() => callSiliconFlowAI(question, imageBase64, currentRequestController.value?.signal))
        message.content = aiResponse
        message.status = 'sent'
      }
    } catch (error) {
      console.error(t('retryFailed'), error)
      message.status = 'failed'
    } finally {
      isLoading.value = false
      currentThinkingStep.value = ''
    }
  }
}

// 添加语音相关的响应式变量
const isRecording = ref(false)
const recognition = ref<any>(null)
const synthesis = window.speechSynthesis

// 语音识别
const startVoiceInput = () => {
  if ('webkitSpeechRecognition' in window) {
    recognition.value = new (window as any).webkitSpeechRecognition()
    recognition.value!.continuous = false
    recognition.value!.interimResults = false
    recognition.value!.lang = 'zh-CN'
    
    recognition.value!.onstart = () => {
      isRecording.value = true
      showToast('开始录音...')
    }
    
    recognition.value!.onresult = (event: any) => {
      const transcript = event.results[0][0].transcript
      userInput.value = transcript
      isRecording.value = false
    }
    
    recognition.value!.onerror = () => {
      isRecording.value = false
      showToast('语音识别失败')
    }
    
    recognition.value!.start()
  } else {
    showToast('浏览器不支持语音识别')
  }
}

// 语音播报AI回复
const speakText = (text: string) => {
  if (synthesis) {
    const utterance = new SpeechSynthesisUtterance(text)
    utterance.lang = 'zh-CN'
    utterance.rate = 0.8
    synthesis.speak(utterance)
  }
}

// 添加聊天记录持久化
const saveChatHistory = () => {
  try {
    const historyToSave = chatHistory.value.map(msg => ({
      ...msg,
      timestamp: msg.timestamp.toISOString()
    }))
    localStorage.setItem('ai_chat_history', JSON.stringify(historyToSave))
  } catch (error) {
    console.warn(t('saveHistoryFailed'), error)
  }
}

const loadChatHistory = () => {
  try {
    const saved = localStorage.getItem('ai_chat_history')
    if (saved) {
      const parsed = JSON.parse(saved)
      chatHistory.value = parsed.map((msg: any) => ({
        ...msg,
        timestamp: new Date(msg.timestamp)
      }))
    }
  } catch (error) {
    console.warn(t('loadHistoryFailed'), error)
  }
}

// 监听聊天历史变化并保存
watch(chatHistory, saveChatHistory, { deep: true })

// 智能建议基于用户历史
const getPersonalizedSuggestions = () => {
  const recentTopics = chatHistory.value
    .slice(-10)
    .map(msg => msg.content)
    .join(' ')
  
  // 基于历史对话生成个性化建议
  if (recentTopics.includes('减肥')) {
    return ['有氧运动计划', '饮食建议', '卡路里计算']
  } else if (recentTopics.includes('增肌')) {
    return ['力量训练', '蛋白质摄入', '训练计划']
  }
  return quickQuestions.value.map(q => q.text)
}

// 组件挂载时添加欢迎消息
onMounted(() => {
  // 先加载历史记录
  loadChatHistory()
  
  // 如果没有历史记录，添加欢迎消息
  if (chatHistory.value.length === 0) {
    chatHistory.value.push({
      id: Date.now(),
      content: t('welcomeMessage'),
      type: 'ai',
      timestamp: new Date(),
      status: 'sent'
    })
  }
})

// 统一的按钮点击处理
const handleMainButtonClick = async () => {
  await sendMessage()
}

// 添加textarea自动调整高度功能
const autoResizeTextarea = (event: Event) => {
  const textarea = event.target as HTMLTextAreaElement
  if (textarea) {
    // 重置高度以获取正确的scrollHeight
    textarea.style.height = 'auto'
    
    // 计算新高度（最小1行，最大5行）
    const lineHeight = 24 // 每行高度
    const minHeight = lineHeight + 24 // 1行 + padding
    const maxHeight = lineHeight * 5 + 24 // 5行 + padding
    
    const newHeight = Math.min(Math.max(textarea.scrollHeight, minHeight), maxHeight)
    textarea.style.height = newHeight + 'px'
    
    // 如果内容超过最大高度，显示滚动条
    textarea.style.overflowY = textarea.scrollHeight > maxHeight ? 'auto' : 'hidden'
  }
}

// 处理键盘事件
const handleKeyDown = (event: KeyboardEvent) => {
  if (event.key === 'Enter') {
    // Ctrl+Enter 或 Shift+Enter 换行
    if (event.ctrlKey || event.shiftKey) {
      return // 允许换行
    }
    // 单独按Enter发送消息
    event.preventDefault()
    debouncedSendMessage()
  }
}

// 添加输入防抖，避免频繁触发
const debouncedSendMessage = debounce(sendMessage, 300)

// 组件卸载时清理
onUnmounted(() => {
  // 清理请求控制器
  if (currentRequestController.value) {
    currentRequestController.value.abort()
  }
  
  // 清理图片预览URL
  if (imagePreview.value) {
    URL.revokeObjectURL(imagePreview.value)
  }
})
</script>

<template>
  <div class="chat-container">
    <div class="chat-header">
      <div class="header-left">
        <button class="back-button" @click="goBack">
          <i class="back-icon">←</i>
        </button>
      </div>
      <h2>{{ t('aiFitnessAssistant') }}</h2>
      <div class="header-controls">
        <!-- 回退按钮 -->
        <button 
          v-if="canUndo" 
          class="control-btn undo-btn" 
          @click="undoLastMessage"
          :title="t('undoTooltip')">
          ↶
        </button>
        
        <!-- 删除最后一条消息 -->
        <button 
          v-if="chatHistory.length > 1" 
          class="control-btn delete-btn" 
          @click="deleteLastMessage"
          :title="t('deleteTooltip')">
          🗑️
        </button>
      </div>
    </div>
    
    
    <div class="chat-messages">
      <div v-for="message in chatHistory" :key="message.id" 
           :class="['message', message.type === 'user'? 'user-message' : 'ai-message']">
        <!-- 显示图片（如果有） -->
        <div v-if="message.image" class="message-image">
          <img :src="message.image" :alt="t('userImageAlt')" />
        </div>
        <!-- 显示视频（如果有） -->
        <div v-if="message.video" class="message-video">
          <video :src="message.video" controls></video>
        </div>
        <div class="message-content">
          {{ message.content }}
          <span v-if="message.type === 'ai' && isLoading && message === chatHistory[chatHistory.length - 1] && useStreaming" class="cursor"></span>
          <!-- 语音播报按钮 -->
          <button 
            v-if="message.type === 'ai' && message.content"
            @click="speakText(message.content)"
            class="speak-btn"
            title="语音播报">
            🔊
          </button>
        </div>
        <div class="message-footer">
          <div class="message-time">
            {{ new Date(message.timestamp).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'}) }}
          </div>
          <!-- 消息状态和重试按钮 -->
          <div v-if="message.type === 'ai'" class="message-status">
            <span v-if="message.status === 'sending'" class="status-sending">{{ t('sending') }}</span>
            <span v-else-if="message.status === 'sent'" class="status-sent">✓</span>
            <button v-else-if="message.status === 'failed'" @click="retryMessage(message.id)" class="retry-btn">
              {{ t('retry') }} {{ message.retryCount? `(${message.retryCount}/3)` : '' }}
            </button>
          </div>
        </div>
        <!-- 显示思考过程 -->
        <div v-if="showThinking && message.thinking && message.thinking.length > 0" class="thinking-process">
          <div class="thinking-header">{{ t('thinkingProcess') }}:</div>
          <div v-for="(thought, index) in message.thinking" :key="index" class="thinking-step">
            {{ index + 1 }}. {{ thought }}
          </div>
        </div>
      </div>
      
      <!-- 显示当前思考步骤 -->
      <div v-if="isLoading && currentThinkingStep && showThinking" class="message ai-message thinking-message">
        <div class="thinking-indicator">
          <span>{{ t('thinking') }}</span>
          <span class="dots"><span>.</span><span>.</span><span>.</span></span>
        </div>
        <div class="current-thinking">{{ currentThinkingStep }}</div>
      </div>
      
      <!-- 加载指示器 (仅在非流式模式下显示) -->
      <div v-else-if="isLoading &&!useStreaming" class="message ai-message loading">
        <div class="typing-indicator">
          <span></span>
          <span></span>
          <span></span>
        </div>
      </div>
    </div>
    

    <!-- 修改常见问题区域 -->
    <div 
      class="quick-questions-panel" 
      :class="{ show: showQuickQuestions }"
      v-if="chatHistory.filter(msg => msg.type === 'user').length < 5">
      <div class="quick-questions-content">
        <h3>常见问题：</h3>
        <div class="question-list">
          <button 
            v-for="question in quickQuestions" 
            :key="question.id"
            @click="selectQuickQuestion(question); showQuickQuestions = false"
            class="quick-question-btn">
            {{ question.text }}
          </button>
        </div>
      </div>
    </div>
    
    <div class="chat-input">
      <!-- 图片预览区域 -->
      <div v-if="imagePreview" class="image-preview">
        <img :src="imagePreview" :alt="t('previewImageAlt')" />
        <button @click="removeImage" class="remove-image-btn" :title="t('removeImage')">×</button>
      </div>
      
      <!-- 视频预览区域 -->
      <div v-if="videoPreview" class="video-preview">
        <video :src="videoPreview" controls></video>
        <button @click="removeVideo" class="remove-video-btn">×</button>
      </div>
      
      <!-- 上传按钮行 -->
      <div class="upload-row">
        <!-- 图片上传按钮 -->
        <label for="imageInput" class="image-upload-btn" :class="{ disabled: isLoading || isUploading }">
          📷 图片
        </label>
        <input 
          id="imageInput"
          type="file" 
          accept="image/*" 
          @change="handleImageUpload"
          style="display: none;"
          :disabled="isLoading || isUploading"
        />
        
        <!-- 视频上传按钮 -->
        <label for="videoInput" class="video-upload-btn" :class="{ disabled: isLoading || isUploading }">
          🎥 视频
        </label>
        <input 
          id="videoInput"
          type="file" 
          accept="video/*" 
          @change="handleVideoUpload"
          style="display: none;"
          :disabled="isLoading || isUploading"
        />
        
        <!-- 常见问题切换按钮 -->
        <button 
          @click="toggleQuickQuestions"
          :class="['quick-questions-toggle-btn', { active: showQuickQuestions }]"
          title="常见问题">
          <span class="toggle-icon">💬</span>
          <span class="toggle-text">{{ showQuickQuestions ? '隐藏问题' : '常见问题' }}</span>
        </button>
      </div>
      
      <!-- 输入框和发送按钮行 -->
      <div class="input-row">
        <div class="input-container">
          <textarea 
            v-model="userInput" 
            @input="autoResizeTextarea"
            @keydown="handleKeyDown"
            :placeholder="selectedImage ? '描述图片或提问...' : selectedVideo ? '描述视频或提问...' : '输入您的问题...'"
            :disabled="isLoading || isUploading"
            rows="1"
            class="chat-textarea"
          ></textarea>
          
          <!-- 语音输入按钮（放在输入框内） -->
          <button 
            @click="startVoiceInput" 
            :disabled="isLoading || isUploading || isRecording"
            :class="['voice-input-btn', { recording: isRecording }]"
            title="语音输入">
            🎤
          </button>
        </div>
        
        <button 
          @click="handleMainButtonClick" 
          :disabled="buttonState.disabled"
          :class="['smart-send-btn']"
          :title="buttonState.text">
          <span class="btn-icon">{{ buttonState.icon }}</span>
          <span class="btn-text">{{ buttonState.text }}</span>
        </button>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 基础容器优化 */
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  height: 100dvh; /* 动态视口高度，避免移动端键盘遮挡 */
  max-width: 100%;
  background-color: #f5f5f5;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  position: relative;
}

/* 增强头部视觉效果 */
.chat-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: clamp(10px, 2.5vw, 15px) clamp(12px, 3vw, 20px);
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  position: sticky;
  top: 0;
  z-index: 100;
  backdrop-filter: blur(20px);
  box-shadow: 0 2px 20px rgba(0, 0, 0, 0.1);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  flex-wrap: nowrap;
  gap: 12px;
  min-height: 60px;
}

.header-left {
  display: flex;
  align-items: center;
  flex-shrink: 0;
}

.back-button {
  background: none;
  border: none;
  color: white;
  font-size: 1.2rem;
  cursor: pointer;
  padding: 8px 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 6px;
  transition: background-color 0.2s ease;
  min-width: 44px;
  height: 44px;
}

.back-button:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.back-icon {
  font-style: normal;
  font-weight: bold;
  font-size: 1.4rem;
}

.chat-header h2 {
  margin: 0;
  font-size: clamp(1rem, 4vw, 1.2rem);
  flex: 1;
  text-align: center;
  min-width: 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 控制按钮组 - 只包含回退和删除按钮 */
.header-controls {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-shrink: 0;
  justify-content: flex-end;
  flex-wrap: wrap;
}

/* 统一按钮基础样式 - 减少重复代码 */
.btn-base {
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  white-space: nowrap;
  user-select: none;
}

/* 优化控制按钮样式 */
.control-btn {
  background-color: rgba(255, 255, 255, 0.15);
  color: white;
  padding: 8px 12px;
  border-radius: 6px;
  cursor: pointer; 
  transition: all 0.2s ease;
  min-width: 44px;
  height: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
  white-space: nowrap;
  backdrop-filter: blur(5px);
}



.control-btn:hover {
  background-color: rgba(255, 255, 255, 0.25);
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}



.control-btn:active {
  transform: translateY(0);
}



.undo-btn {
  font-size: 1.2rem;
  font-weight: bold;
}

.delete-btn {
  font-size: 1rem;
}



/* 消息区域优化 */
.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: clamp(10px, 3vw, 15px);
  display: flex;
  flex-direction: column;
  gap: clamp(8px, 2vw, 10px);
  /* 性能优化 */
  -webkit-overflow-scrolling: touch;
  scroll-behavior: smooth;
  will-change: scroll-position;
  contain: layout style paint;
}

/* 优化消息渲染性能 */
.message {
  max-width: clamp(250px, 80%, 600px);
  padding: clamp(10px, 2.5vw, 16px) clamp(12px, 3vw, 18px);
  border-radius: 18px;
  margin-bottom: clamp(6px, 1.5vw, 8px);
  position: relative;
  word-wrap: break-word;
  word-break: break-word;
  hyphens: auto;
  /* 性能优化 */
  contain: layout style;
  transform: translateZ(0); /* 启用硬件加速 */
  animation: fadeInUp 0.3s ease-out;
}

/* 优化消息气泡样式 */
.user-message {
  align-self: flex-end;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-bottom-right-radius: 5px;
  box-shadow: 0 2px 12px rgba(102, 126, 234, 0.3);
}

.ai-message {
  align-self: flex-start;
  color: #333;
  border-bottom-left-radius: 5px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(0, 0, 0, 0.05);
}

.message-time {
  font-size: 0.7rem;
  opacity: 0.7;
  margin-top: 5px;
  text-align: right;
}

/* 思考过程样式 */
.thinking-process {
  margin-top: 10px;
  font-size: 0.8rem;
  color: #666;
  background-color: rgba(0, 0, 0, 0.03);
  padding: 8px;
  border-radius: 8px;
  border-left: 3px solid #999;
}

.thinking-header {
  font-weight: bold;
  margin-bottom: 5px;
  color: #555;
}

.thinking-step {
  margin-bottom: 3px;
  padding-left: 5px;
}

.thinking-message {
  background-color: rgba(0, 0, 0, 0.05);
}

.thinking-indicator {
  display: flex;
  align-items: center;
  font-size: 0.9rem;
  color: #6c757d;
  margin-bottom: 8px;
  animation: thinking 2s ease-in-out infinite;
}

.dots span {
  animation: dots 1.5s infinite;
  opacity: 0;
}

.dots span:nth-child(1) {
  animation-delay: 0s;
}

.dots span:nth-child(2) {
  animation-delay: 0.3s;
}

.dots span:nth-child(3) {
  animation-delay: 0.6s;
}

@keyframes dots {
  0%, 100% { opacity: 0; }
  50% { opacity: 1; }
}

.current-thinking {
  font-style: italic;
}

/* 输入区域响应式优化 */
.chat-input {
  display: flex;
  flex-direction: column;
  padding: clamp(8px, 2vw, 12px);
  background-color: white;
  border-top: 1px solid #ddd;
  position: sticky;
  bottom: 0;
  /* 确保在虚拟键盘弹出时正确显示 */
  bottom: env(keyboard-inset-height, 0);
}

/* 修改：输入行样式 */
.input-row {
  display: flex;
  gap: 8px;
  align-items: center;
  margin-top: 10px;
}

/* 按钮响应式优化 */
.smart-send-btn {
  display: flex;
  align-items: center;
  gap: clamp(4px, 1vw, 6px);
  background-color: #0084ff;
  color: white;
  border: none;
  border-radius: 20px;
  padding: clamp(8px, 2vw, 12px) clamp(16px, 4vw, 20px);
  cursor: pointer;
  font-size: clamp(0.9rem, 2.5vw, 1rem);
  transition: all 0.3s ease;
  min-width: clamp(70px, 15vw, 90px);
  justify-content: center;
  white-space: nowrap;
}

.chat-input button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

/* 常见问题切换按钮样式 */
.quick-questions-toggle-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  padding: 10px 16px;
  background-color: #f8f9fa;
  border: 1px solid #ddd;
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 14px;
  color: #333;
  min-height: 40px;
  position: relative;
  overflow: hidden;
}

.quick-questions-toggle-btn:hover {
  background-color: #e9ecef;
  border-color: #667eea;
  transform: translateY(-1px);
}

.quick-questions-toggle-btn.active {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-color: #667eea;
}

.quick-questions-toggle-btn.active:hover {
  background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
}

.toggle-icon {
  font-size: 16px;
  transition: transform 0.3s ease;
}

.quick-questions-toggle-btn.active .toggle-icon {
  transform: rotate(180deg);
}

/* 常见问题面板样式 */
.quick-questions-panel {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  border-top: 1px solid #e0e0e0;
  border-radius: 16px 16px 0 0;
  box-shadow: 0 -4px 20px rgba(0, 0, 0, 0.1);
  transform: translateY(100%);
  transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  z-index: 1000;
  max-height: 50vh;
  overflow-y: auto;
}

.quick-questions-panel.show {
  transform: translateY(0);
}

.quick-questions-content {
  padding: 20px;
}

.quick-questions-content h3 {
  margin: 0 0 16px 0;
  font-size: 18px;
  color: #333;
  text-align: center;
  position: relative;
}

.quick-questions-content h3::after {
  content: '';
  position: absolute;
  bottom: -8px;
  left: 50%;
  transform: translateX(-50%);
  width: 40px;
  height: 3px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 2px;
}

.question-list {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 12px;
  max-height: 300px;
  overflow-y: auto;
}

.quick-question-btn {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border: 1px solid #dee2e6;
  border-radius: 12px;
  padding: 12px 16px;
  font-size: 14px;
  color: #495057;
  cursor: pointer;
  transition: all 0.2s ease;
  text-align: left;
  line-height: 1.4;
  min-height: 48px;
  display: flex;
  align-items: center;
}

.quick-question-btn:hover {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-color: #667eea;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.quick-question-btn:active {
  transform: translateY(0);
}

/* 移动端适配 */
@media (max-width: 768px) {
  .quick-questions-toggle-btn {
    padding: 8px 12px;
    font-size: 13px;
    min-height: 36px;
  }
  
  .toggle-text {
    display: none;
  }
  
  .quick-questions-panel {
    max-height: 60vh;
  }
  
  .quick-questions-content {
    padding: 16px;
  }
  
  .question-list {
    grid-template-columns: 1fr;
    gap: 8px;
  }
  
  .quick-question-btn {
    padding: 10px 12px;
    font-size: 13px;
    min-height: 44px;
  }
}

/* 超小屏幕适配 */
@media (max-width: 480px) {
  .quick-questions-toggle-btn {
    padding: 6px 10px;
    min-height: 32px;
  }
  
  .toggle-icon {
    font-size: 14px;
  }
}

/* 添加遮罩层效果（可选） */
.quick-questions-panel::before {
  content: '';
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
  opacity: 0;
  visibility: hidden;
  transition: all 0.3s ease;
  z-index: -1;
}

.quick-questions-panel.show::before {
  opacity: 1;
  visibility: visible;
}

.typing-indicator {
  display: flex;
  padding: 6px 10px;
  gap: 4px;
}

.typing-indicator span {
  height: 8px;
  width: 8px;
  background-color: #999;
  border-radius: 50%;
  display: inline-block;
  animation: bounce 1.5s infinite ease-in-out;
}

.typing-indicator span:nth-child(1) {
  animation-delay: 0s;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes bounce {
  0%, 60%, 100% {
    transform: translateY(0);
  }
  30% {
    transform: translateY(-4px);
  }
}

/* 图片相关样式 */
.message-image {
  margin-bottom: 8px;
}

/* 图片和视频预览优化 */
.message-image img {
  max-width: min(300px, 70vw); /* 响应式图片大小 */
  max-height: min(300px, 40vh);
  border-radius: 8px;
  object-fit: cover;
  cursor: pointer;
  transition: transform 0.2s;
}

.message-image img:hover {
  transform: scale(1.05);
}

/* 视频相关样式 */
.message-video {
  margin-bottom: 8px;
}

.message-video video {
  max-width: min(400px, 80vw);
  max-height: min(300px, 50vh);
  border-radius: 8px;
  object-fit: cover;
}

.video-preview {
  position: relative;
  margin-bottom: 10px;
  display: inline-block;
}

.video-preview video {
  max-width: clamp(120px, 25vw, 180px);
  max-height: clamp(80px, 15vw, 120px);
  border-radius: 8px;
  object-fit: cover;
  border: 2px solid #ddd;
}

.remove-video-btn {
  position: absolute;
  top: -8px;
  right: -8px;
  background-color: #ff4444;
  color: white;
  border: none;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  font-size: 12px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  line-height: 1;
}

.image-preview {
  position: relative;
  margin-bottom: 10px;
  display: inline-block;
}

.image-preview img {
  max-width: clamp(80px, 20vw, 120px);
  max-height: clamp(80px, 20vw, 120px);
  border-radius: 8px;
  object-fit: cover;
  border: 2px solid #ddd;
}

.remove-image-btn {
  position: absolute;
  top: -8px;
  right: -8px;
  background-color: #ff4444;
  color: white;
  border: none;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  font-size: 12px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  line-height: 1;
}

.input-row {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 新增：上传按钮行样式 */
.upload-row {
  display: flex;
  gap: 12px;
  margin-bottom: 12px;
  justify-content: flex-start;
  align-items: center;
}

/* 修改：输入框容器样式 */
.input-container {
  position: relative;
  flex: 1;
  display: flex;
  align-items: center;
}

/* 修改：输入框样式 */
.chat-textarea {
  width: 100%;
  padding: 12px 45px 12px 15px; /* 右侧留出语音按钮空间 */
  border: 1px solid #ddd;
  border-radius: 25px;
  font-size: 16px;
  outline: none;
  transition: all 0.2s ease;
  background-color: white;
  color: #333; /* 添加明确的文本颜色 */
  resize: none; /* 禁用手动调整大小 */
  font-family: inherit;
  line-height: 1.5;
  min-height: 48px;
  max-height: 144px; /* 5行的最大高度 */
  overflow-y: hidden;
}

.input-container input:focus,
.input-container .chat-textarea:focus {
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1);
}

/* textarea特定样式 */
.chat-textarea {
  scrollbar-width: thin;
  scrollbar-color: #ccc transparent;
}

.chat-textarea::-webkit-scrollbar {
  width: 6px;
}

.chat-textarea::-webkit-scrollbar-track {
  background: transparent;
}

.chat-textarea::-webkit-scrollbar-thumb {
  background-color: #ccc;
  border-radius: 3px;
}

.chat-textarea::-webkit-scrollbar-thumb:hover {
  background-color: #999;
}

/* 调整语音按钮位置以适应textarea */
.voice-input-btn {
  position: absolute;
  right: 10px;
  bottom: 10px; /* 调整为bottom定位，适应textarea高度变化 */
  transform: none;
  background: none;
  border: none;
  font-size: 18px;
  cursor: pointer;
  padding: 8px;
  border-radius: 50%;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 36px;
  height: 36px;
}

.voice-input-btn:hover {
  background-color: rgba(102, 126, 234, 0.1);
}

.voice-input-btn.recording {
  background-color: #ff4757;
  color: white;
  animation: pulse 1s infinite;
}

@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.1); }
  100% { transform: scale(1); }
}

/* 修改：上传按钮样式 */
.image-upload-btn,
.video-upload-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  padding: 10px 16px;
  background-color: #f8f9fa;
  border: 1px solid #ddd;
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 14px;
  color: #333;
  text-decoration: none;
  min-height: 40px;
}

.image-upload-btn:hover,
.video-upload-btn:hover {
  background-color: #e9ecef;
  border-color: #667eea;
  transform: translateY(-1px);
}

.image-upload-btn.disabled,
.video-upload-btn.disabled {
  opacity: 0.5;
  cursor: not-allowed;
  pointer-events: none;
}

.chat-input {
  display: flex;
  flex-direction: column;
  padding: 10px;
  background-color: white;
  border-top: 1px solid #ddd;
  position: sticky;
  bottom: 0;
}

.chat-input input {
  flex: 1;
  padding: 10px 15px;
  border: 1px solid #ddd;
  border-radius: 20px;
  outline: none;
  font-size: 1rem;
}

/* 修改：发送按钮样式 */
.smart-send-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 25px;
  padding: 12px 20px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  gap: 6px;
  min-height: 48px;
  white-space: nowrap;
}

.smart-send-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.5);
  background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
}

.smart-send-btn:active {
  transform: translateY(-1px);
}

.smart-send-btn.pause {
  background-color: #ffc107;
  color: #333;
}

.smart-send-btn.pause:hover:not(:disabled) {
  background-color: #e0a800;
  box-shadow: 0 4px 8px rgba(255, 193, 7, 0.3);
}

.smart-send-btn.resume {
  background-color: #28a745;
}

.smart-send-btn.resume:hover:not(:disabled) {
  background-color: #218838;
  box-shadow: 0 4px 8px rgba(40, 167, 69, 0.3);
}

.smart-send-btn:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.btn-icon {
  font-size: 1.1em;
  line-height: 1;
}

.btn-text {
  font-weight: 500;
}

/* 按钮状态切换动画 */
.smart-send-btn {
  animation: buttonStateChange 0.3s ease;
}

@keyframes buttonStateChange {
  0% { transform: scale(1); }
  50% { transform: scale(1.05); }
  100% { transform: scale(1); }
}



/* 语音播报按钮样式 */
.speak-btn {
  background: none;
  border: none;
  font-size: 14px;
  cursor: pointer;
  margin-left: 8px;
  padding: 4px;
  border-radius: 4px;
  opacity: 0.6;
  transition: opacity 0.2s;
}

.speak-btn:hover {
  opacity: 1;
  background-color: rgba(0, 0, 0, 0.1);
}

/* 平板设备适配 (768px - 1024px) */
@media (min-width: 481px) and (max-width: 1024px) {
  .chat-container {
    max-width: 800px;
    margin: 0 auto;
  }
  
  .message {
    max-width: 75%;
  }
  
  .header-controls {
    gap: 10px;
  }
  
  .input-row {
    gap: 12px;
  }
}

/* 大屏设备优化 (1025px+) */
@media (min-width: 1025px) {
  .chat-container {
    max-width: 1000px;
    margin: 0 auto;
    height: calc(100vh - 40px);
    margin-top: 20px;
    border-radius: 12px;
  }
  
  .message {
    max-width: 70%;
  }
  
  .chat-messages {
    padding: 20px;
  }
}

/* 优化移动端体验 */
@media (max-width: 768px) {
  .chat-header {
    padding: 12px 16px;
    gap: 12px;
    min-height: 60px;
  }
  
  .back-button,
  .control-btn {
    min-width: 40px;
    height: 40px;
    padding: 6px 10px;
  }
  
  .chat-header h2 {
    font-size: 1rem;
  }
  
  .header-controls {
    gap: 4px;
  }
  

  
  .message {
    max-width: 85%;
    padding: 12px 16px;
  }
  
  .upload-row {
    gap: 8px;
    margin-bottom: 8px;
  }
  
  .image-upload-btn,
  .video-upload-btn {
    padding: 8px 12px;
    font-size: 13px;
    min-height: 36px;
  }
  
  .input-container textarea {
    padding: 10px 45px 10px 14px;
    font-size: 16px; /* 防止iOS缩放 */
    min-height: 44px;
    max-height: 132px;
  }
  
  .voice-input-btn {
    width: 32px;
    height: 32px;
    right: 6px;
  }
  
  .smart-send-btn {
    padding: 10px 16px;
    min-height: 44px;
  }
  
  .btn-text {
    display: none; /* 小屏只显示图标 */
  }
  
  .input-row {
    gap: 12px;
    padding: 4px 0;
  }
  
  .chat-input {
    padding: 16px;
    background: linear-gradient(to top, #f8f9fa, white);
  }
}

/* 超小屏幕优化 */
@media (max-width: 480px) {
  .header-controls {
    gap: 3px;
  }
  
  .back-button,
  .control-btn {
    min-width: 36px;
    height: 36px;
    padding: 6px;
  }
  

}

/* 横屏模式优化 */
@media (orientation: landscape) and (max-height: 500px) {
  .header-controls {
    gap: 6px;
  }
  

  
  .message {
    max-width: 90%;
    padding: 10px 12px;
  }
  
  .input-row {
    flex-wrap: nowrap;
    gap: 6px;
  }
  
  /* 修复快速问题按钮样式 */
  .quick-question-btn {
    font-size: 0.8rem !important;
    padding: 8px 12px !important;
    background-color: white !important;
    border: 1px solid #ddd !important;
    color: #333 !important;
    display: inline-block !important;
    white-space: nowrap !important;
    overflow: visible !important;
    text-overflow: clip !important;
    min-width: fit-content !important;
    max-width: none !important;
  }
  
  .question-list {
    display: flex !important;
    flex-wrap: wrap !important;
    gap: 8px !important;
  }
  

}

/* 超小屏设备 (≤320px) */
@media (max-width: 320px) {
  .chat-header h2 {
    font-size: 1rem;
  }
  
  .message {
    max-width: 95%;
    padding: 8px 10px;
  }
  
  .input-row {
    gap: 4px;
  }
  
  .smart-send-btn {
    padding: 8px 10px;
    min-width: 50px;
  }
}

@media (orientation: landscape) and (max-height: 500px) {
  .chat-header {
    padding: 8px 15px;
  }
  
  .chat-messages {
    padding: 10px 15px;
  }
  
  .chat-input {
    padding: 8px 15px;
  }
  
  .quick-questions {
    display: none; /* 横屏时隐藏快速问题以节省空间 */
  }
}

/* 改进焦点样式 */
.control-btn:focus,
.smart-send-btn:focus,
.quick-question-btn:focus {
  outline: 2px solid #667eea;
  outline-offset: 2px;
}

.chat-input textarea:focus {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
  outline: none;
}

/* 高对比度模式支持 */
@media (prefers-contrast: high) {
  .message {
    border: 2px solid currentColor;
  }
  
  .control-btn {
    border: 2px solid white;
  }
}

/* 高对比度和可访问性优化 */
@media (prefers-reduced-motion: reduce) {
  * {
    animation-duration: 0.01ms !important;
    animation-iteration-count: 1 !important;
    transition-duration: 0.01ms !important;
  }
}

@media (prefers-color-scheme: dark) {
  .chat-container {
    background-color: #1a1a1a;
    color: #ffffff;
  }
  
  .chat-header {
    background-color: #2d2d2d;
  }
  
  .ai-message {
    background-color: #3a3a3a;
    color: #ffffff;
  }
  
  .chat-input {
    background-color: #2d2d2d;
    border-top-color: #444;
  }
  
  .chat-input input,
  .chat-input .chat-textarea {
    background-color: #3a3a3a;
    border-color: #555;
    color: #ffffff;
  }
}

/* 优化思考动画 */
@keyframes thinking {
  0%, 100% { opacity: 0.4; }
  50% { opacity: 1; }
}

/* 优化加载动画 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 打印样式优化 */
@media print {
  .chat-header,
  .chat-input,
  .quick-questions {
    display: none;
  }
  
  .chat-container {
    height: auto;
    box-shadow: none;
  }
  
  .message {
    max-width: 100%;
    break-inside: avoid;
  }
}

/* 添加流式输出相关样式 */


.mode-toggle {
  background-color: rgba(255, 255, 255, 0.2);
  border: none;
  color: white;
  padding: 5px 10px;
  border-radius: 4px;
  font-size: 0.8rem;
  cursor: pointer;
}

.cursor {
  display: inline-block;
  width: 2px;
  height: 16px;
  background-color: #333;
  margin-left: 2px;
  vertical-align: middle;
  animation: blink 1s infinite;
}

@keyframes blink {
  0%, 100% { opacity: 1; }
  50% { opacity: 0; }
}

/* 消息状态和重试按钮样式 */
.message-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 5px;
}

.message-status {
  display: flex;
  align-items: center;
  font-size: 0.7rem;
}

.status-sending {
  color: #999;
  font-style: italic;
}

.status-sent {
  color: #4CAF50;
  font-weight: bold;
}

.retry-btn {
  background-color: #ff6b6b;
  color: white;
  border: none;
  border-radius: 12px;
  padding: 4px 8px;
  font-size: 0.7rem;
  cursor: pointer;
  transition: background-color 0.2s;
}

.retry-btn:hover {
  background-color: #ff5252;
}

.retry-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}



/* 状态指示器样式 */
.status-indicator {
  padding: 10px;
  text-align: center;
  font-weight: bold;
  color: white;
}

.status-indicator.paused {
  background: linear-gradient(45deg, #ffc107, #fd7e14);
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.7; }
  100% { opacity: 1; }
}

/* 响应式设计 */
@media (max-width: 480px) {
  .header-controls {
    flex-direction: column;
    gap: 4px;
  }
  
  .mode-toggle,
  .thinking-toggle {
    font-size: 0.7rem;
    padding: 4px 8px;
  }
  
  .control-btn {
    font-size: 0.7rem;
    padding: 4px 6px;
    min-width: 28px;
    height: 28px;
  }
  
  .message-footer {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
  
  .retry-btn {
    font-size: 0.6rem;
    padding: 3px 6px;
  }
  
  .status-indicator {
    font-size: 0.8rem;
    padding: 6px 10px;
  }
}

/* 移动端优化 */
@media (max-width: 768px) {
  .chat-textarea {
    font-size: 16px; /* 防止iOS缩放 */
    border-radius: 20px;
    padding: 10px 45px 10px 14px;
  }
  
  .voice-input-btn {
    right: 6px;
    bottom: 5px;
    width: 32px;
    height: 32px;
    font-size: 16px;
  }
}

/* 超小屏幕优化 */
@media (max-width: 480px) {
  .input-container {
    margin-right: 8px;
  }
  
  .chat-textarea {
    padding: 8px 40px 8px 12px;
    min-height: 44px;
  }
}
</style>